﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AmkeniCrossLoginApplication.Data_Access;
using AmkeniCrossLoginApplication.Reports;

namespace AmkeniCrossLoginApplication
{
    public partial class Default : ReportCreator
    {
        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            generateIpsPerCall();
            generateCallPieCharts();
            generateSummaryofReports();
            generateSummaryOfProjectImplementationBarChart();
            generateSummaryofProjectImplementationStatus();
            generateBeneficiariesSummary();

            if (!User.IsInRole("Administrator"))
            {
                Dash.Visible = false;
            }
            else
            {
                Dash.Visible = true;
            }
        }

        protected void generateIpsPerCall()
        {
            var _calls = (from data in db.RFPs select data);
            foreach (var call in _calls)
            {
                TableCell ipCell = new TableCell();
                ipRow.Cells.Add(ipCell);

                //Create a new IP table for each cell created above
                Table ipTable = new Table();
                ipCell.Controls.Add(ipTable);

                TableHeaderRow headerRow = new TableHeaderRow();
                ipTable.Rows.Add(headerRow);
                TableHeaderCell headerCell = new TableHeaderCell();
                headerCell.Text = call.RFP_name;
                headerRow.Cells.Add(headerCell);

                var _IPs = (from data in db.implementing_partner_metadata
                            where data.RFP_id == call.RFP_id
                            select data);
                foreach (var ip in _IPs)
                {
                    TableRow tRow = new TableRow();
                    ipTable.Rows.Add(tRow);
                    TableCell tCell = new TableCell();
                    tCell.Text = ip.implementing_partner.abbreviation;
                    tRow.Cells.Add(tCell);
                }
            }
        }

        protected void generateBeneficiariesSummary()
        {
            var _calls = (from data in db.ip_direct_beneficiary select data.RFP_id).Distinct();
            headerRowCell.ColumnSpan = _calls.Count();
            foreach (var call in _calls)
            {
                TableCell beneficiariesCell = new TableCell();
                beneficariesRow.Cells.Add(beneficiariesCell);

                //Create a new beneficiaries table for each call
                Table beneficiariesTable = new Table();
                beneficiariesCell.Controls.Add(beneficiariesTable);

                //This adds the header to each table. Thus naming it
                var callName = (from data in db.RFPs
                                where data.RFP_id == call
                                select data.RFP_name).FirstOrDefault();
                TableHeaderRow headerRow = new TableHeaderRow();
                beneficiariesTable.Rows.Add(headerRow);
                TableHeaderCell beneficiariesHeaderCell = new TableHeaderCell();
                beneficiariesHeaderCell.ColumnSpan = 3;
                beneficiariesHeaderCell.Text = callName;
                headerRow.Cells.Add(beneficiariesHeaderCell);

                TableRow header = new TableRow();
                beneficiariesTable.Rows.Add(header);
                TableCell cell1 = new TableCell();
                header.Cells.Add(cell1);
                TableCell maleCell = new TableCell();
                maleCell.Text = "Male";
                header.Cells.Add(maleCell);
                TableCell femaleCell = new TableCell();
                femaleCell.Text = "Female";
                header.Cells.Add(femaleCell);

                int maleCount = 0;
                int femaleCount = 0;
                int indirectBeneficiariesCount = 0;

                var benName = (from data in db.ip_direct_beneficiary
                               where data.RFP_id == call
                               select new { data.beneficiary_id, data.beneficiary }).Distinct();
                foreach (var name in benName)
                {
                    var _count = from data in db.ip_direct_beneficiary
                                 where data.beneficiary_id == name.beneficiary_id &&
                                 data.RFP_id == call
                                 select data;

                    maleCount = 0;
                    femaleCount = 0;

                    foreach (var count in _count)
                    {
                        maleCount += (int)count.male;
                        femaleCount += (int)count.female;
                    }

                    TableRow tRow = new TableRow();
                    beneficiariesTable.Rows.Add(tRow);
                    TableCell tCell1 = new TableCell();
                    tRow.Cells.Add(tCell1);
                    TableCell tCell2 = new TableCell();
                    tRow.Cells.Add(tCell2);
                    TableCell tCell3 = new TableCell();
                    tRow.Cells.Add(tCell3);
                    tCell1.Text = name.beneficiary.name;
                    tCell2.Text = maleCount.ToString("N0");
                    tCell3.Text = femaleCount.ToString("N0");
                }

                var _indirectCount = from data in db.ip_report
                                     where data.RFP_id == call
                                     select data.beneficiaries;

                foreach (var indirectCount in _indirectCount)
                {
                    if (indirectCount != null)
                    {
                        indirectBeneficiariesCount += (int)indirectCount;
                    }
                }

                TableRow tRow1 = new TableRow();
                beneficiariesTable.Rows.Add(tRow1);
                TableCell tCell4 = new TableCell();
                tRow1.Cells.Add(tCell4);
                TableCell tCell5 = new TableCell();
                tCell5.ColumnSpan = 2;
                tRow1.Cells.Add(tCell5);
                tCell4.Text = "Indirect Beneficiaries";
                tCell5.Text = indirectBeneficiariesCount.ToString("N0");
            }
        }

        protected void generateSummaryOfProjectImplementationBarChart()
        {
            var _call = (from data in db.RFPs select data);
            foreach (var call in _call)
            {
                TableCell tCell = new TableCell();
                BarChartTableRow.Cells.Add(tCell);

                AjaxControlToolkit.BarChart callBarChart = new AjaxControlToolkit.BarChart();
                callBarChart.ID = call.RFP_id.ToString();
                callBarChart.ChartTitle = call.RFP_name;
                callBarChart.ChartType = AjaxControlToolkit.BarChartType.Column;
                callBarChart.ChartHeight = "300";
                callBarChart.ChartWidth = "450";
                callBarChart.ChartTitleColor = "#0E426C";
                callBarChart.CategoryAxisLineColor = "#D08AD9";
                callBarChart.ValueAxisLineColor = "#D08AD9";
                callBarChart.BaseLineColor = "#A156AB";

                string IpCategory = string.Empty;
                

                var _IPs = (from data in db.indicator_result
                            where data.RFP_id == call.RFP_id
                            select data.ip_report.implementing_partner).Distinct();

                /*int _delayed = 0;
                int _ongoing = 0;
                int _completed = 0;*/

                if (_IPs.ToList().Count > 0)
                {
                    var IpIds = (from data in db.indicator_result
                                 where data.RFP_id == call.RFP_id
                                 select data.ip_report.implementing_partner.ip_id).Distinct().ToArray();

                    decimal[] delayed = new decimal[IpIds.Count()];
                    decimal[] ongoing = new decimal[IpIds.Count()];
                    decimal[] completed = new decimal[IpIds.Count()];

                    //IEnumerable<indicator_result> _results = null;

                    foreach (var ip in _IPs)
                    {
                        IpCategory = IpCategory + "," + ip.abbreviation;

                        //_results = (from data in db.indicator_result
                        //                where data.ip_id == ip.ip_id
                        //                select data);


                    }

                    //_delayed = (from data in _results where data.status_id == 1 select data).Count();
                    //_ongoing = (from data in _results where data.status_id == 2 select data).Count();
                    //_completed = (from data in _results where data.status_id == 3 select data).Count();

                    for (int i = 0; i < IpIds.Count(); i++)
                    {
                        var tmp = IpIds[i];
                        delayed[i] = (from data in db.indicator_result
                                      where data.ip_id == tmp && data.status_id == 1 &&
                                      data.RFP_id == call.RFP_id
                                      select data).Count();
                        ongoing[i] = (from data in db.indicator_result
                                      where data.ip_id == tmp && data.status_id == 2 &&
                                      data.RFP_id == call.RFP_id
                                      select data).Count();
                        completed[i] = (from data in db.indicator_result
                                        where data.ip_id == tmp && data.status_id == 3 &&
                                      data.RFP_id == call.RFP_id
                                        select data).Count();
                    }

                    callBarChart.CategoriesAxis = IpCategory.Remove(0, 1).Trim();
                    callBarChart.Series.Add(new AjaxControlToolkit.BarChartSeries
                            {
                                Name = "Delayed",
                                BarColor = "#FF0000",
                                Data = delayed
                            });
                    callBarChart.Series.Add(new AjaxControlToolkit.BarChartSeries
                        {
                            Name = "OnGoing",
                            BarColor = "#FFFF00",
                            Data = ongoing
                        });
                    callBarChart.Series.Add(new AjaxControlToolkit.BarChartSeries
                        {
                            Name = "Completed",
                            BarColor = "#00FF00",
                            Data = completed
                        });
                    tCell.Controls.Add(callBarChart);
                }
            }
        }

        protected void generateSummaryofProjectImplementationStatus()
        {
            var _call = from data in db.RFPs select data;
            foreach (var call in _call)
            {
                ImplementationHeader.ColumnSpan = _call.Count();
                TableCell callCell = new TableCell();
                ImplementationCallRow.Cells.Add(callCell);

                var _implementingPartners = (from data in db.indicator_result
                                            where data.RFP_id == call.RFP_id
                                            select data.ip_report.implementing_partner).Distinct();

                Table statusTable = new Table();
                TableHeaderRow headerRow = new TableHeaderRow();
                statusTable.Rows.Add(headerRow);
                TableHeaderCell headerCell = new TableHeaderCell();
                headerCell.ColumnSpan = _call.Count();
                headerCell.Text = call.RFP_name;
                headerRow.Cells.Add(headerCell);

                foreach (var implementingPartner in _implementingPartners)
                {
                    var _results = (from data in db.indicator_result
                                    where data.ip_id == implementingPartner.ip_id
                                    select data);

                    int delayed = (from data in _results where data.status_id == 1 select data).Count();
                    int ongoing = (from data in _results where data.status_id == 2 select data).Count();
                    int completed = (from data in _results where data.status_id == 3 select data).Count();

                    int[] allStatus = new int[3] { delayed, ongoing, completed };
                    //Array.Sort(allStatus);

                    //Iterate through the array, keeping track of the largest value seen 
                    //so far and the index of that value
                    /*var largest = -1;
                    var status = -1;

                    for (var i = 0; i < allStatus.Length; ++i)
                    {
                        if (allStatus[i] > largest)
                        {
                            status = i;
                            largest = allStatus[i];
                        }
                    }*/

                    TableRow tRow = new TableRow();
                    statusTable.Rows.Add(tRow);

                    TableCell tCell1 = new TableCell();
                    tRow.Cells.Add(tCell1);
                    tCell1.Text = implementingPartner.abbreviation;

                    TableCell tCell2 = new TableCell();
                    tRow.Cells.Add(tCell2);
                    if ((delayed > ongoing) && (delayed > completed))
                    {
                        tCell2.Text = "Delayed";
                        tCell2.BackColor = System.Drawing.Color.Red;
                    }
                    else if (((ongoing > delayed) && (ongoing > completed)) ||
                        ((delayed == ongoing)&&(ongoing == completed)))
                    {
                        tCell2.Text = "On Going";
                        tCell2.BackColor = System.Drawing.Color.Yellow;
                    }
                    else if ((completed > delayed) && (completed > ongoing))
                    {
                        tCell2.Text = "Completed";
                        tCell2.BackColor = System.Drawing.Color.Green;
                    }
                    else if ((delayed == ongoing) && (delayed > completed))
                    {
                        tCell2.Text = "Delayed/Ongoing";
                    }
                    else if ((ongoing == completed) && (ongoing > delayed))
                    {
                        tCell2.Text = "Ongoing/Completed";
                    }
                    
                }
                callCell.Controls.Add(statusTable);
            }
        }

        protected void generateSummaryofReports()
        {
            int numberOfSavedReports = (from data in db.ip_report where data.saved == true select data).Count();
            int numberOfSubmittedReports = (from data in db.ip_report where data.submitted == true select data).Count();
            int numberOfApprovedReports = (from data in db.ip_report where data.approved == true select data).Count();
            int numberofArchivedReports = (from data in db.ip_report where data.archived == true select data).Count();

            TableCell tCellSaved = new TableCell();
            savedRow.Cells.Add(tCellSaved);
            tCellSaved.Text = numberOfSavedReports.ToString();

            TableCell tCellSubmitted = new TableCell();
            submittedRow.Cells.Add(tCellSubmitted);
            tCellSubmitted.Text = numberOfSubmittedReports.ToString();

            TableCell tCellApproved = new TableCell();
            approvedRow.Cells.Add(tCellApproved);
            tCellApproved.Text = numberOfApprovedReports.ToString();

            TableCell tCellArchived = new TableCell();
            archivedRow.Cells.Add(tCellArchived);
            tCellArchived.Text = numberofArchivedReports.ToString();

        }

        protected void generateCallPieCharts()
        {
            var _theCall = (from data in db.RFPs select data);
            foreach (var theCall in _theCall)
            {
                decimal totalExpenditure = 0;
                decimal balanceOfFunds = 0;
                /*TableRow CallTableRow = new TableRow();
                CallTable.Rows.Add(CallTableRow);*/

                var _ipPerCall = (from data in db.ip_report where data.RFP_id == theCall.RFP_id select data.ip_id).Distinct();
                foreach (var ipPerCall in _ipPerCall)
                {
                    var totalExp = (from data in db.ip_report
                                    where data.ip_id == ipPerCall &&
                                    data.RFP_id == theCall.RFP_id
                                    select data.total_cfs).OrderByDescending(x => x.Value).First();

                    if (totalExp.HasValue)
                    {
                        totalExpenditure += (decimal)totalExp;
                    }
                }
                //if()
                balanceOfFunds = (decimal)(theCall.budget - totalExpenditure);

                //Create the table columns and corresponding pie charts
                TableCell tcell = new TableCell();
                CallTableRow.Cells.Add(tcell);

                AjaxControlToolkit.PieChart callPieChart = new AjaxControlToolkit.PieChart();
                callPieChart.ID = theCall.RFP_name;
                callPieChart.ChartTitle = theCall.RFP_name;
                callPieChart.ChartHeight = "300";
                callPieChart.ChartWidth = "450";
                callPieChart.ChartTitleColor = "#0E426C";
                callPieChart.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
                {
                    Category = "Total Expenditure",
                    Data = totalExpenditure,
                    PieChartValueColor = "#D08AD9",
                    PieChartValueStrokeColor = "black"
                });
                callPieChart.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
                    {
                        Category = "Balance of Funds",
                        Data = balanceOfFunds,
                        PieChartValueColor = "#6C1E83",
                        PieChartValueStrokeColor = "black"
                    });

                tcell.Controls.Add(callPieChart);
            }
        }

        protected void AgreementsButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Amkeni_Monitoring_Plan/WorkPlanView.aspx");
            //Response.Redirect("../Amkeni_Monitoring_Plan/WorkPlan.aspx");
        }
        protected void QuarterlyReportsButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Amkeni_System/Home.aspx");
            //Response.Redirect("../Amkeni_System/Home.aspx");
        }

        protected void GenerateReportButton_Click(object sender, EventArgs e)
        {
            int call = int.Parse(CallList.SelectedValue.Trim());
            int year = int.Parse(YearList.SelectedValue.Trim());
            int reportPeriod = int.Parse(ReportPeriodList.SelectedValue.Trim());
            int reportType = int.Parse(ReportTypeList.SelectedValue.Trim());

            if (reportType == 1)
            {
                createNarrativeReport(call, year, reportPeriod);
            }
            else if (reportType == 2)
            {
                createResultsReport(call, year, reportPeriod);
            }
            else if (reportType == 3)
            {
                createM_and_EReport(call, year, reportPeriod);
            }
            else if (reportType == 4)
            {
                createSuccessStoryReport(call, year, reportPeriod);
            }
            else if (reportType == 5)
            {
                createUpcomingActivitiesReport(call, year, reportPeriod);
            }
            else if (reportType == 6)
            {
                createRiskandMitigationReport(call, year, reportPeriod);
            }
            else if (reportType == 7)
            {
                createPhotographsReport(call, year, reportPeriod);
            }
        }
    }
}